import Cookies from 'js-cookie'

export const state = () => ({
  isLoginOpen: false,
  isEditProfileOpen: false,
  selectedPost: null,
  ids: null,
  isBackUrl: "/",
  posts: null,
  suggested: null,
  following: null,
})

export const mutations = {
  reverse(state) {
    state.ids.reverse()
  },
  change_isLoginOpen(state, data) {
    state.isLoginOpen = data
  },
  change_isEditProfileOpen(state, data) {
    state.isEditProfileOpen = data
  },
  getRandomUsers(state, {type, data}) {
    if (type === 'suggested') {
      state.suggested = data.data.suggested
    }
    if (type === 'following') {
      state.following = data.data.following
    }
  },
  bodySwitch(state, val) {
    if (val) {
      document.body.style.overflow = 'hidden'
      return
    }
    document.body.style.overflow = 'visible'
  },
  allLowerCaseNoCaps(state, str) {
    return str.split(' ').join('').toLowerCase()
  },
  setBackUrl(state, url) {
    state.isBackUrl = url
  },
  change_selectedPost(state) {
    state.selectedPost = null
  },
  updateSideMenuImage(state, {array, user}) {
    for (let i = 0; i < array.length; i++) {
      const res = array[i];
      if (res.id == user.id) {
        res.image = user.image
      }
    }
  },
  updateSideMenuUser(state, {array, user}) {
    for (let i = 0; i < array.length; i++) {
      const res = array[i];
      if (res.id == user.id) {
        res.name = user.name
        res.bio = user.bio
      }
    }
  },
  getAllUsersAndPosts(state, res) {
    state.posts = res.data
  },
  getPostById(state, res) {
    state.selectedPost = res.data.post[0]
    state.ids = res.data.ids
  },
}
export const actions = {
  hasSessionExpired({commit}) {
    this.$axios.interceptors.response.use((response) => {
      // Call was successful, continue.
      return response;
    }, (error) => {
      switch (error.response && error.response.status) {
        case 401: // Not logged in
          Cookies.remove('laravel_session') // value
          Cookies.remove('XSRF-TOKEN') // value
          commit('user/resetUser', '', {root: true})
          let r = confirm('登录已过期')
          if (r) {
            window.location.href = '/';
          } else {
            window.location.href = '/';
          }
          break;
        case 419: // Session expired
        case 503: // Down for maintenance
          commit('user/resetUser', '', {root: true})
          window.location.href = '/';
          break;
        case 500:
          alert('Oops, something went wrong!  The team has been notified.');
          break;
        default:
          return Promise.reject(error);
      }
    });
  },

  async getPostById({commit}, id) {
    let res = await this.$axios.get(`/api/posts/${id}`)
    commit('getPostById', res)
  },

  async getRandomUsers({commit}, type) {
    let res = await this.$axios.get(`/api/get-random-users`)
    commit('getRandomUsers', {type: type, data: res})
  },

  async getAllUsersAndPosts({commit}) {
    let res = await this.$axios.get('/api/home')
    commit('getAllUsersAndPosts', res)
  }
}
